#!/bin/bash

# Usage:   copy-libs  $share_path

# This file is designed to run on CentOS 6.7 but may work on other systems.

main() {
  # Set sources:
  qt_prefix="$(locateQt)"
  echo "qt_prefix: $qt_prefix"

  # Set destinations:
  [ "$1" ] && share_path="$1" || share_path="."
  lib_dest="$share_path/lib"
  qt_dest="$lib_dest/qt5"
  opt_dest="$share_path/optional" # Workaround for Jack library loading
  echo "lib_dest: $lib_dest"
  echo "qt_dest: $qt_dest"

  num_failures=0 # store number of libraries that couldn't be copied
  getCrossPlatformDependencies

  # get linux-specific dependencies, based on which distro is making the AppImage
  if [ "$(grep "Debian GNU/Linux 8 (jessie)" /etc/*release*)" ]; then
    building_on_Debian_Jessie # aka "Debian 8"
  elif [ "$(grep "CentOS release 6" /etc/*release*)" ]; then
    building_on_CentOS_6
  else
    echo "${0}: Warning: Not running on a supported build system!" >&2
    # Try to fetch all dependencies, just in case
    building_on_CentOS_6
  fi

  if [ "$num_failures" != "0" ]; then
    echo "Error: $num_failures libraries couldn't be copied."
    exit 1
  fi
}

##########################################################################
# LINUX EQUIVALENTS OF WINDOWS DEPENDENCIES (see "mscore/CMakeLists.txt")
##########################################################################
getCrossPlatformDependencies() {
  # Non-Qt dependencies (see "mscore/CMakeLists.txt")
  dest_dir="$lib_dest"
  #copyLib libgcc_s_dw2-1.so # Assume provided by system
  #copyLib libstdc++-6.so # Assume provided by system
  #copyLib libwinpthread-1.so # Assume provided by system
  #copyLib libogg.so # Assume provided by system
  #copyLib libsndfile-1.so # Assume provided by system
  #copyLib libvorbis.so # Assume provided by system
  #copyLib libvorbisfile.so # Assume provided by system
  copyLib libportaudio.so.2
  copyLib libportmidi.so
  copyLib libporttime.so
  #copyLib libeay32.so # Assume provided by system
  #copyLib ssleay32.so # Assume provided by system

  # Qt base dependencies (see "mscore/CMakeLists.txt")
  dest_dir="$qt_dest/lib"
  #dest_dir="$lib_dest"

  #icudata, icui18n, & icuuc have version numbers (.52 when build on jessie,
  #.42 on centos) so moved to cross-platform for the time being.
  #copyLib libicudata.so #icudt53.dll # Needed by Ubuntu 12.04
  #copyLib libicui18n.so #libicuin53.so.5 # Needed by Ubuntu 12.04
  #copyLib libicuuc.so #libicuuc53.so.5 # Needed by Ubuntu 12.04

  copyLib libQt5CLucene.so.5
  copyLib libQt5Core.so.5
  copyLib libQt5Gui.so.5
  copyLib libQt5Help.so.5
  copyLib libQt5Multimedia.so.5
  copyLib libQt5MultimediaWidgets.so.5
  copyLib libQt5Network.so.5
  copyLib libQt5OpenGL.so.5
  copyLib libQt5Positioning.so.5
  copyLib libQt5PrintSupport.so.5
  copyLib libQt5Qml.so.5
  copyLib libQt5Quick.so.5
  copyLib libQt5QuickControls2.so.5
  copyLib libQt5QuickTemplates2.so.5
  copyLib libQt5Sensors.so.5
  copyLib libQt5Sql.so.5
  copyLib libQt5Svg.so.5
  copyLib libQt5WebChannel.so.5
  copyLib libQt5Widgets.so.5
  copyLib libQt5XmlPatterns.so.5
  copyLib libQt5Xml.so.5

  # Qt components (see "mscore/CMakeLists.txt")
  copyQt plugins/iconengines/libqsvgicon.so

  copyQt plugins/imageformats/libqgif.so
  copyQt plugins/imageformats/libqjpeg.so
  copyQt plugins/imageformats/libqmng.so
  copyQt plugins/imageformats/libqsvg.so
  copyQt plugins/imageformats/libqtiff.so

  copyQt plugins/platforms/libqxcb.so #qwindows.dll

  copyQt plugins/printsupport/libcupsprintersupport.so #windowsprintersupport.dll

  copyQt plugins/sqldrivers/libqsqlite.so

  # recursively copy everything in the Qt QML directory
  # except some as listed in "mscore/CMakeLists.txt".
  export -f copy copyQt # make functions available to xargs
  find "$qt_prefix/qml" \! -type d \
    | grep -vE "QtMultimedia|QtSensors|QtTest|QtWebEngine" \
    | sed "s|$qt_prefix/||" | xargs -n1 -I '%%%' \
        bash -c "qt_prefix='$qt_prefix' qt_dest='$qt_dest' copyQt %%%"
}

########################################################
# copy libs specific if building on Debian 8 "Jessie"
########################################################
building_on_Debian_Jessie() {
  dest_dir="$lib_dest"
  copyLib libasound.so.2
  copyLib libcups.so.2
  copyLib libdbus-1.so && mv "$dest_dir/libdbus-1.so" "$dest_dir/libdbus-1.so.3" #renamed to .3 because didn't exist in arm, and don't want x86-64 fallback version
  copyLib libEGL.so.1
  copyLib libfontconfig.so.1
  copyLib libfreetype.so.6
  copyLib libGLESv2.so.2
  copyLib libglib-2.0.so && mv "$dest_dir/libglib-2.0.so" "$dest_dir/libglib-2.0.so.0" #renamed to .0 cause didn't have
  copyLib libgobject-2.0.so.0
  copyLib libgstapp-0.10.so.0
  copyLib libgstbase-0.10.so.0
  copyLib libgstinterfaces-0.10.so.0
  copyLib libgstpbutils-0.10.so.0
  copyLib libgstreamer-0.10.so.0
  copyLib libgstvideo-0.10.so.0
  copyLib libharfbuzz.so.0
  copyLib libICE.so.6
  copyLib liblcms2.so.2
  copyLib libogg.so.0
  copyLib libSM.so.6
  copyLib libsndfile.so.1
  copyLib libsqlite3.so.0
  copyLib libtiff.so.5
  copyLib libvorbis.so.0
  copyLib libvorbisfile.so.3
  copyLib libwebp.so.5
  copyLib libX11-xcb.so.1
  copyLib libX11.so.6
  copyLib libxcb-icccm.so.4
  copyLib libxcb-image.so.0
  copyLib libxcb-keysyms.so.1
  copyLib libxcb-randr.so.0
  copyLib libxcb-render-util.so.0
  copyLib libxcb-render.so.0
  copyLib libxcb-shape.so.0
  copyLib libxcb-shm.so.0
  copyLib libxcb-sync.so.1
  copyLib libxcb-xfixes.so.0
  copyLib libxcb-xkb.so.1
  copyLib libxcb.so.1
  copyLib libXi.so.6
  copyLib libxkbcommon-x11.so.0
  copyLib libxkbcommon.so.0
  copyLib libxml2.so.2
  copyLib libxslt.so.1

  copyLib libicudata.so.56 # moved from cross-platform
  copyLib libicui18n.so.56 # moved from cross-platform
  copyLib libicuuc.so.56 # moved from cross-platform

  #2nd round of dependencies
  copyLib libavahi-client.so.3
  copyLib libavahi-common.so.3
  copyLib libdrm.so.2
  copyLib libexpat.so && mv "$dest_dir/libexpat.so" "$dest_dir/libexpat.so.1" #renamed to .1 cause didn't have
  copyLib libffi.so.6
  copyLib libFLAC.so.8
  copyLib libgbm.so.1
  copyLib libglapi.so.0
  copyLib libgmodule-2.0.so.0
  copyLib libgnutls-deb0.so.28
  copyLib libgraphite2.so.3
  copyLib libgssapi_krb5.so.2
  copyLib libgthread-2.0.so.0
  copyLib libjbig.so.0
  copyLib libjson-c.so && mv "$dest_dir/libjson-c.so" "$dest_dir/libjson-c.so.2" #renamed to .2 cause didn't have
  copyLib liborc-0.4.so.0
  copyLib libvorbisenc.so.2
  copyLib libwayland-client.so.0
  copyLib libwayland-server.so.0
  copyLib libXau.so.6
  copyLib libxcb-dri2.so.0
  copyLib libxcb-util.so.0
  copyLib libXdmcp.so.6
  copyLib libXext.so.6

  #3rd round of dependencies
  copyLib libasyncns.so.0
  copyLib libgmp.so.10
  copyLib libhogweed.so.2
  copyLib libjpeg.so.62
  copyLib libk5crypto.so.3
  copyLib libkeyutils.so && mv "$dest_dir/libkeyutils.so" "$dest_dir/libkeyutils.so.1" #renamed to .1 cause didn't have
  copyLib libkrb5.so.3
  copyLib libkrb5support.so.0
  copyLib libmng.so.1
  copyLib libnettle.so.4
  copyLib libp11-kit.so.0
  copyLib libpng12.so.0

  copyLib libtasn1.so.6
  copyLib libwrap.so.0
  copyLib libXtst.so.6
  dest_dir="$qt_dest/lib"
  copyLib libQt5Concurrent.so.5
  copyLib libQt5DBus.so.5
  copyLib libQt5Designer.so.5
  copyLib libQt5QuickWidgets.so.5
  copyLib libQt5Test.so.5

  #jessie doesn't seem to have the following, although in sid this is provided by libqt5gui5
  #copyLib libQt5XcbQpa.so.5
  #copyQt plugins/xcbglintegrations/libqxcb-glx-integration.so # Needed by plugins which open a window

  #needed by Arch Linux
  dest_dir="$lib_dest"
  copyLib libpcre.so.3

  # needed if don't have pulseaudio installed (e.g. in a minimal chroot on Android)
  copyLib libpulse.so.0
  copyLib libpulsecommon-5.0.so

  # Workaround for Jack library
  dest_dir="$opt_dest"
  copyLib libjack.so.0

  # If AppImage is run with alsa, then will complain:
  # "Cannot open shared library /usr/lib/arm-linux-gnueabihf/alsa-lib/libasound_module_pcm_pulse.so"
  # but cannot seem to figure out how to get the AppImage, so exclude for now, hopefully figure out later.
  #dest_dir="$lib_dest/alsa-lib"
  #copyLib libasound_module_pcm_pulse.so #can add, but if mscore run without alsa, will complain missing
}


##########################################################################
# LINUX-ONLY DEPENDENCIES (no equivalents in "mscore/CMakeLists.txt")
# These differ depending on the distribution used to build the AppImage.
# Note: always check the oldest supported distribution first
##########################################################################
building_on_CentOS_6() {
  # Needed by Centos 6.7:
  dest_dir="$lib_dest"
  copyLib libopenal.so.1
  dest_dir="$qt_dest/lib"
  copyLib libQt5Concurrent.so.5
  copyLib libQt5DBus.so.5
  copyLib libQt5Designer.so.5
  copyLib libQt5QuickWidgets.so.5
  copyLib libQt5Test.so.5
  copyLib libQt5XcbQpa.so.5
  copyQt plugins/xcbglintegrations/libqxcb-glx-integration.so # Needed by plugins which open a window

  # Needed by Ubuntu 12.04:
  dest_dir="$lib_dest"
  copyLib libcrypto.so.10
  copyLib libjpeg.so.62
  copyLib libssl.so.10
  copyLib libtiff.so.3
  copyLib libicudata.so.56 # moved from cross-platform
  copyLib libicui18n.so.56 # moved from cross-platform
  copyLib libicuuc.so.56 # moved from cross-platform

  # Needed by Fedora 22:
  copyLib libmng.so.1
  copyLib libpng12.so.0
  copyLib libudev.so.0
  copyLib liblcms.so.1

  # Needed if don't have pulseaudio installed. Ignoring, since only advanced distros
  # like Arch, Gentoo, Debian minimal, servers, etc. don't have pulse installed.
  #copyLib libpulse.so.0
  #copyLib libpulsecommon-8.0.so
  #copyLib libasound_module_pcm_pulse.so  # found in /usr/lib64/alsa-lib/

  # after upgrade to Qt 5.6, check-depends in CentOS 6 said following were provided by neither
  copyLib libEGL.so.1
  copyLib libcups.so.2

  # Workaround for Jack library
  dest_dir="$opt_dest"
  copyLib libjack.so.0
}

locateLib() {
  # First search $LD_LIBRARY_PATH
  declare -a dir_array
  IFS=':' read -ra dir_array <<< "${LD_LIBRARY_PATH}"
  for d in "${dir_array[@]}"; do
    if [ -e "$d/$1" ]; then
      echo "$d/$1"
      return
    else
      path="$(ls "$d/$1."* | grep -Em1 "$1.[0-9]+")"
      if [ "$path" ]; then
        echo "$path"
        return
      fi
    fi
  done
  # If it wasn't found then search library cache
  local path="$(ldconfig -p | awk '{print $4}' | grep "$1" | head -n1)"
  [ "$path" ] || echo "$1 not found." >&2
  echo "$path"
}

locateQt() {
  local file="plugins/platforms/libqxcb.so"
  local core_path="$(dirname "$(locateLib "libQt5Core.so.5")")"
  while [ true ]; do
    path="$(ls "$core_path/../$file" 2>/dev/null)"
    [ "$path" ] && break
    # Some distros package Qt plugins in weird places...
    path="$(ls "$core_path/qt5/$file" 2>/dev/null)"
    [ "$path" ] && break
    path="$(find "$core_path" -name "$(basename "$file")" 2>/dev/null)" && break
    [ "$path" ] && break
    # Still not found... Look everywhere except places that might give false
    # positive. Probably best not enable this as as it might find the wrong Qt.
    # path="$(locate "$file" | grep -vEm1 "Audacity|QtCreator")"
    # [ "$path" ] && break
    echo "$0: Couldn't find Qt." >&2
    return 1
  done
  for i in {1..3}; do
    path="$(dirname "$path")"
  done
  echo $path
}

copy() {
  echo "$0: copying $1 to $dest_dir"
  mkdir -p "$dest_dir"
  cp -L -u "$1" -t "$dest_dir" || num_failures="$(($num_failures+1))"
}

copyLib() {
  copy "$(locateLib $1)"
}

copyQt() {
  dest_dir="$qt_dest/$(dirname "$1")"
  copy "$qt_prefix/$1"
}

main "$@"
